package com.rpc.protocal.codec;

import com.rpc.protocal.MsgHeader;
import com.rpc.protocal.RpcProtocol;
import com.rpc.protocal.serilization.RpcSerialization;
import com.rpc.protocal.serilization.RpcSerializationFactory;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * RpcEncoder
 *
 * @author 春江花朝秋月夜
 * @since 2024/1/16 21:13
 */
public class RpcEncoder extends MessageToByteEncoder<RpcProtocol<Object>> {


    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, RpcProtocol<Object> msg, ByteBuf byteBuf) throws Exception {
       /*
       * 将消息写入编码缓冲区里面*/
       //通过RpcProtocol获取header
        MsgHeader msgHeader= msg.getHeader();
        //序列化亲求数据
        byteBuf.writeByte(msgHeader.getMagic());
        byteBuf.writeByte(msgHeader.getVersion());
        byteBuf.writeByte(msgHeader.getMsgType());
        byteBuf.writeByte(msgHeader.getStatus());

        byteBuf.writeLong(msgHeader.getRequestId());
        // 写入序列化方式(接收方需要依靠具体哪个序列化进行序列化),约定好
        byteBuf.writeInt(msgHeader.getSerializationLen());

        final byte[] ser = msgHeader.getSerializations();
        byteBuf.writeBytes(ser);
        final String serialization = new String(ser);

        RpcSerialization rpcSerialization= RpcSerializationFactory.get(serialization);
        //写入数据
        byte[]data=rpcSerialization.serialize(msg.getBody());
        byteBuf.writeBytes(data);
    }
}
